﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.IO;
using System.Web.Hosting;

namespace LearningEnglish.ThridAPI
{
    public class DownYoudaoMp3
    {

        public static string Down(string word)
        {
            if (string.IsNullOrWhiteSpace(word))
                throw new Exception("单词名为空");
            word = word.Trim();
            var filePath = HostingEnvironment.MapPath("~/StaticFiles/Audio/" + word + ".mp3");

            var task = Task.Run(
               async () =>
               {
                   HttpClient client = new HttpClient();
                   var response = await client.GetAsync("http://dict.youdao.com/dictvoice?type=2&audio=" + word);
                   var stream = await response.Content.ReadAsStreamAsync();

                   var reader = new BinaryReader(stream);

                   var fileStream = new FileStream(filePath, FileMode.CreateNew);
                   var writer = new BinaryWriter(fileStream);

                   try
                   {

                       while (true)
                       {
                           var line = reader.ReadBytes(10240);
                           if (line.Length == 0)
                               break;
                           writer.Write(line);
                       }
                   }
                   catch (Exception e)
                   {
                       throw e;
                   }
                   finally
                   {
                       reader.Close();
                       writer.Close();
                   }

               });
            task.Wait();
            if (task.Exception != null)
                throw new Exception(task.Exception.Message);
            return filePath;
        }
    }
}